package com.jzr.bedside.base

import android.app.Application
import android.content.Context
import android.content.Intent
import androidx.multidex.MultiDex
import com.blankj.utilcode.utils.CrashUtils
import com.blankj.utilcode.utils.ThreadPoolUtils
import com.blankj.utilcode.utils.Utils
import com.jzr.bedside.service.WebSocketServer
import com.jzr.bedside.service.nettyUtils.NettyService
import com.jzr.bedside.utils.PreferUtil
import com.zhangke.websocket.WebSocketHandler
import com.zhangke.websocket.WebSocketSetting


class BaseApplication : Application() {


    companion object {

        private var mContext: Context? = null
        private var instance: BaseApplication? = null

        var MAIN_EXECUTOR = ThreadPoolUtils(ThreadPoolUtils.Type.FixedThread, 10)

        fun getContext(): Context? {
            return mContext
        }

        fun getInstance(): BaseApplication? {
            return instance
        }
    }

    override fun onCreate() {
        super.onCreate()
        mContext = applicationContext
        initLogger()
        Utils.init(this)
        PreferUtil.getInstance().init(this)
        CrashUtils.getInstance().init()
//        startNettyServer()
        initWebSocket()
        startWebSocketServer()
        instance = this

    }

    private fun  startNettyServer(){
        startService(Intent(this, NettyService::class.java))
    }
    private fun  startWebSocketServer(){
        startService(Intent(this, WebSocketServer::class.java))
    }

    private fun initWebSocket() {
        val setting = WebSocketSetting()
        //连接地址，必填，例如 wss://echo.websocket.org
//        setting.connectUrl = "ws://192.168.250.104:8013/ws" //必填
        setting.connectUrl = "ws://10.100.100.44:8013/ws" //必填
        //设置连接超时时间
        setting.connectTimeout = 15 * 1000
        //设置心跳间隔时间
        setting.connectionLostTimeout = 40
        //设置断开后的重连次数，可以设置的很大，不会有什么性能上的影响
        setting.reconnectFrequency = 999999
        //网络状态发生变化后是否重连，
        //需要调用 WebSocketHandler.registerNetworkChangedReceiver(context) 方法注册网络监听广播
        setting.setReconnectWithNetworkChanged(true)
        //通过 init 方法初始化默认的 WebSocketManager 对象
        val manager = WebSocketHandler.init(setting)
        //启动连接
        manager.start()
        //注意，需要在 AndroidManifest 中配置网络状态获取权限
        //注册网路连接状态变化广播
        WebSocketHandler.registerNetworkChangedReceiver(this)
    }


    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        MultiDex.install(this)
    }

    private fun initLogger() {
//        Logger.init("ART").methodCount(2).methodOffset(0)
//            .logLevel(LogLevel.FULL).hideThreadInfo()
    }

}